package kr.co.hk.date;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import kr.co.hk.R;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class DatePlaceList extends ListActivity {

	private ArrayList<MyItem> aMyItem = new ArrayList<MyItem>();
	private MyListAdapter MyAdapter;

	private boolean isChk = false;
	
	private String url = "";
	private int page = 1;
	private ProgressDialog progressDialog;
	final private int PROGRESS_DIALOG = 0;
	private boolean gubun = false;
	private boolean pageEx = false;
	private BufferedReader br;
	private ArrayList<String> br_list;
	private Bundle extra;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.date_list);
		MyAdapter = new MyListAdapter(this, R.layout.date_row, aMyItem);
		setListAdapter(MyAdapter);
		
		
		Spinner sp = (Spinner) findViewById(R.id.spRidName);
		Button btnNext = (Button) findViewById(R.id.btnDateNext);
		Button btnBack = (Button) findViewById(R.id.btnDateBack);
		
		ArrayAdapter spAdapter = ArrayAdapter.createFromResource(this,
				R.array.alt_ridName, android.R.layout.simple_spinner_item);

		spAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp.setAdapter(spAdapter);
		br_list = new ArrayList<String>();
		extra = getIntent().getExtras();
		gubun = extra.getBoolean("gubun");
		btnBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				int backPage= page -1;
				if(backPage < 1){
					toast("첫페이지 입니다.");
				}else{
					page= backPage;
					String more_url = url + "&page=" + backPage;
					isChk = false;
					aMyItem.clear();
					threadStart(more_url);
				}
			}
		});
		
		btnNext.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (isChk) {
					int nextPage= page +1;
					page= nextPage;
					String more_url = url + "&page=" + nextPage;
					isChk = false;
					aMyItem.clear();
					threadStart(more_url);
				}else{
					toast("더 이상 없습니다.");
				}
				
				
			}
		});
		sp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int spPosition, long arg3) {
			
				isChk = false;
				page = 1;
				aMyItem.clear();
				Resources resources = getResources();
				String[] ridArr = resources.getStringArray(R.array.rid);
				
				url = extra.getString("url") + "&rid=" + ridArr[spPosition];

				mainProcessing();
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});

		getListView().setOnItemClickListener(listlistener);
	}

	private Handler chdHandler = new Handler();

	private void mainProcessing() {
		pageEx = false;
		showDialog(PROGRESS_DIALOG);
		Thread childThread = new Thread(null, dobackgroundThreadProcessing,
				"Backgroud");
		childThread.start();
	}

	private Runnable dobackgroundThreadProcessing = new Runnable() {

		@Override
		public void run() {
			backgroudnThreadProcessing();
		}
	};

	private void backgroudnThreadProcessing() {
		getDateList(url);
		chdHandler.post(doUpdateGUI);
	}

	private Runnable doUpdateGUI = new Runnable() {

		@Override
		public void run() {
			updateGUI();
		}
	};

	private void updateGUI() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		progressDialog.dismiss();
		DatePlaceList.this.removeDialog(PROGRESS_DIALOG);
		
		if(pageEx){
			excePro();
		}else{
			MyAdapter.notifyDataSetChanged();
			getListView().setSelectionFromTop(0, 1);
		}
	}

	private void threadStart(final String html) {
		pageEx = false;
		showDialog(PROGRESS_DIALOG);
		new Thread() {
			public void run() {
				getDateList(html);
				Message msg = handler.obtainMessage();
				handler.sendMessage(msg);
			}
		}.start();
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			DatePlaceList.this.removeDialog(PROGRESS_DIALOG);
			if(pageEx){
				excePro();
			}else{
				MyAdapter.notifyDataSetChanged();
				getListView().setSelectionFromTop(0, 1);
			}
		}
	};
	

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case PROGRESS_DIALOG:

			progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("Now loading..");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(false);
			return progressDialog;

		}
		return null;

	}
	
	
	private void excePro(){
		toast("페이지 로딩시 오류가  있습니다. \n 네트워크 확인 후 다시 시도 하세요!");
		onBackPressed();
	}

	private OnItemClickListener listlistener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			String url = aMyItem.get(position).link;
			Intent intent = new Intent(DatePlaceList.this,
					DatePlaceDetail.class);
			intent.putExtra("url", url);
			intent.putExtra("gubun", gubun);
			startActivity(intent);
		}

	};

	public void getDateList(String addr) {
		try {
			URL url = new URL(addr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			if (conn != null) {
				conn.setConnectTimeout(10000);
				conn.setReadTimeout(10000);
				conn.setUseCaches(false);

				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					br = new BufferedReader(new InputStreamReader(conn
							.getInputStream(), "utf-8"));

					String msg = "";
					br_list.clear();
					while ((msg = br.readLine()) != null) {
						br_list.add(msg.trim() + "\n");
					}
					String title = "";
					String link = "";
					String imageLink = "";
					String date = "";
					isChk = false;
					int startIndex = 0;
					if (br_list.size() > 0) {
						if (gubun) {
							startIndex = 1500;
						} else {
							startIndex = 300;
						}

					}
					for (int i = startIndex; i < br_list.size(); i++) {
						String line = br_list.get(i);

						String reStr = line;
						int firstIndex = 0;
						int lastIndex = 0;

						if (line.contains("class=\"next\"")) {
							isChk = true;

						}
						// title
						if (line.contains("class=\"col_tit\"")) {
							// false : 맛집, 여행, 이색 true: 데이트명소
							if (gubun) {
								reStr = br_list.get(i + 1);
								firstIndex = reStr.indexOf("\">");
								lastIndex = reStr.indexOf("</a>");
								title = reStr.substring(firstIndex + 2,
										lastIndex).replace("&#39;", "");

								firstIndex = reStr.indexOf("http");
								lastIndex = reStr.indexOf("\">");
								link = reStr.substring(firstIndex, lastIndex);
							} else {
								reStr = br_list.get(i);
								firstIndex = reStr.indexOf("&count=5\">");
								lastIndex = reStr.indexOf("</a>");
								title = reStr.substring(firstIndex + 10,
										lastIndex).replace("&#39;", "");

								firstIndex = reStr.indexOf("http");
								lastIndex = reStr.indexOf("&count=5");
								link = reStr.substring(firstIndex,
										lastIndex + 8).replace("&#39;", "");
							}

						}
						if (line.contains("class=\"col_img_tit\"")) {
							if (gubun) {
								reStr = br_list.get(i);
								firstIndex = reStr.indexOf("src=");
								lastIndex = reStr.indexOf("onerror");
								imageLink = reStr.substring(firstIndex + 5,
										lastIndex - 2);

							} else {
								reStr = br_list.get(i);
								firstIndex = reStr.indexOf("src=");
								lastIndex = reStr.indexOf("alt");
								imageLink = reStr.substring(firstIndex + 5,
										lastIndex - 2);

							}

						}

						if (line.contains("<span class=\"date\">")) {
							reStr = br_list.get(i);
							firstIndex = reStr.indexOf("\">");
							lastIndex = reStr.indexOf("</span");
							date = reStr.substring(firstIndex + 2, lastIndex);

							
							
							InputStream is = new URL(imageLink).openStream();

							BitmapFactory.Options options = new BitmapFactory.Options();
							options.inSampleSize = 4;
							options.inScaled = false;
							Bitmap src = BitmapFactory.decodeStream(is, null, options);
							
							Bitmap resized;

							if (src != null) {
								
								int density = src.getDensity();
								int width = src.getWidth();
								int height = src.getHeight();
								resized = Bitmap.createScaledBitmap(src, width, height,
										true);
								
								resized.setDensity(density);
							} else {
								options.inSampleSize = 1;
								options.inScaled = false;
								resized = BitmapFactory.decodeStream(is, null, options);

							}

							MyItem item = new MyItem(resized, title, date, link);
							aMyItem.add(item);
							
							

						}
					}
					br.close();

				}
				conn.disconnect();
			}
		} catch (Exception ex) {
			pageEx = true;
			ex.printStackTrace();
		}
	}

	private void toast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}
}

class MyItem {
	Bitmap bits;
	String contents;
	String contents2;
	String link;

	MyItem(Bitmap bit, String content, String content2, String link) {
		this.bits = bit;
		this.contents = content;
		this.contents2 = content2;
		this.link = link;
	}
}

class MyListAdapter extends BaseAdapter {
	Context maincon;
	LayoutInflater Inflater;
	ArrayList<MyItem> aitem;
	int alayout;

	public MyListAdapter(Context context, int layout, ArrayList<MyItem> item) {
		maincon = context;
		Inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		alayout = layout;
		aitem = item;
	}

	public int getCount() {
		return aitem.size();
	}

	public String getItem(int position) {
		return aitem.get(position).contents;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		final int pos = position;
		if (convertView == null) {
			convertView = Inflater.inflate(alayout, parent, false);
		}

		ImageView img = (ImageView) convertView.findViewById(R.id.dateRowImg);
		img.setImageBitmap(aitem.get(pos).bits);

		TextView tv = (TextView) convertView.findViewById(R.id.toptext);
		tv.setText(aitem.get(pos).contents);

		TextView tv1 = (TextView) convertView.findViewById(R.id.bottomtext);
		tv1.setText(aitem.get(pos).contents2);

		return convertView;
	}
}
